vim编辑文件时,系统崩溃后的文件恢复

您所在的位置:网站首页 linux崩溃 恢复 vim编辑文件时,系统崩溃后的文件恢复

vim编辑文件时,系统崩溃后的文件恢复

2024-07-12 13:59| 来源: 网络整理| 查看: 265

描述 :

        在vim编辑文件时,连接异常断开,导致所做的修改没有保存。这时可以通过文件相同目录下的.swp文件来恢复。如果是自己的连接异常断开,确定不需要保存之前的修改,可以直接删掉.swp文件即可。

vim在编辑文件时,是在work buffer中进行的,缓存中的信息有存放在.swp文件(原文件名加.swp结尾的文件),当连接异常断开,缓存中的信息丢失,但.swp文件依然存在,可以通过这个文件来进行数据恢复。如果原文件是正常关闭,.swp文件会自动删除。在正常的修改操作期间,可以不需要.swp文件(比如被误删除了),数据仍能正常从work buffer保存到磁盘,其隐患就是,如果连接异常断开就不能恢复了。

模拟修改文件时异常断开情境,查看文件内容-->修改文件内容-->异常断开连接:

[root@ ~]# cat test.txt oh,this is ddddd 11111 22222 [root@ ~]# vim test.txt oh,this is ddddd 11111 22222 xxxxx

查看需要恢复文件的.swp临时交换文件:

[root@ ~]# ll -a |grep test.txt -rw-r--r--. 1 root root 30 Jul 8 09:03 test.txt -rw-r--r--. 1 root root 12288 Jul 8 09:04 .test.txt.swp

以恢复模式(-r参数)打开文件 ,如下是恢复提示,建议先将恢复后的文件内容保存在另一个文件中,这时原文件不受影响,内容还是修改前的内容,再比较两个文件的内容,确认之前所做的修改。

[root@ ~]# vim -r test.txt Using swap file ".test.txt.swp" Original file "~/test.txt" Recovery completed. You should check if everything is OK. (You might want to write out this file under another name and run diff with the original file to check for changes) Delete the .swp file afterwards. Press ENTER or type command to continue

保存到另一个文件退出,再查看文件:

:w test_r.txt :q [root@ ~]# ll -a |grep test -rw-r--r--. 1 root root 36 Jul 8 09:50 test_r.txt -rw-r--r--. 1 root root 30 Jul 8 09:03 test.txt -rw-r--r--. 1 root root 12288 Jul 8 09:04 .test.txt.swp

比较两个文件的差异,可以看到test_r.txt文件中是多了最后一行的内容:

[root@ ]# diff -y test.txt test_r.txt oh,this is oh,this is ddddd ddddd 11111 11111 22222 22222 > xxxxx

比较完文件内容后,可以确定是否要保存.swp中的信息;可以用-r参数打开原文件,直接:wq保存即可。再删掉.swp文件。

附:

vim中-r参数的使用:

[root@ ~]# man vim -r List swap files, with information about using them for recovery. -r {file} Recovery mode. The swap file is used to recover a crashed editing session. The swap file is a file with the same filename as the text file with ".swp" appended. See ":help recovery".

查看当前目录下的.swp文件:

[root@ ~]# vim -r Swap files found: In current directory: 1. .test.txt.swp owned by: root dated: Mon Jul 8 09:04:05 2019 file name: ~root/test.txt modified: YES user name: root host name: kaka1 process ID: 3168 In directory ~/tmp: -- none -- In directory /var/tmp: -- none -- In directory /tmp: -- none --

以恢复模式打开test.txt文件,这时显示的是.swp文件中的信息:

[root@ ~]# vim -r test.txt

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3